/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package canteen.sys.view;

import canteen.sys.model.entity.TypeOfUse;
import canteen.sys.model.generic.HibernateDAOFactory;
import java.util.Calendar;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import org.hibernate.HibernateException;

/**
 *
 * @author TNT
 */
public class TypeOfUseM extends javax.swing.JInternalFrame implements ActionView<TypeOfUse> {

    HibernateDAOFactory hibernateDAOFactory = HibernateDAOFactory.getInstance();
    DefaultTableModel modelTableTypeOfUse;
    List<TypeOfUse> listTypeOfUse;

    /**
     * Creates new form TypeOfUseM
     */
    public TypeOfUseM() {
        initComponents();
        modelTableTypeOfUse = (DefaultTableModel) tbtypeofuse.getModel();
        if (listTypeOfUse == null) {
            listTypeOfUse = hibernateDAOFactory.getTypeOfUseDAO().findAllByStatus(true);
            showList(listTypeOfUse);
        } else {
            showList(null);
        }
        listenerTableModel();
        listSelectionListener();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtname = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtdescription = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbtypeofuse = new javax.swing.JTable();
        rbstatus = new javax.swing.JRadioButton();
        jLabel3 = new javax.swing.JLabel();
        cbstatus = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        btaddnew = new javax.swing.JButton();
        btrefresh = new javax.swing.JButton();
        btdelete = new javax.swing.JButton();

        setClosable(true);
        setTitle("Đơn vị sử dụng");
        setToolTipText("");

        jLabel1.setText("Tên đơn vị: ");

        txtdescription.setColumns(20);
        txtdescription.setRows(5);
        jScrollPane1.setViewportView(txtdescription);

        jLabel2.setText("Mô tả: ");

        tbtypeofuse.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null},
                {null, null},
                {null, null},
                {null, null}
            },
            new String [] {
                "Đơn vị", "Trạng thái"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane2.setViewportView(tbtypeofuse);
        tbtypeofuse.getColumnModel().getColumn(1).setMaxWidth(100);

        rbstatus.setSelected(true);

        jLabel3.setText("Trạng thái");

        cbstatus.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Hiện", "Ẩn" }));
        cbstatus.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbstatusActionPerformed(evt);
            }
        });

        jLabel4.setText("Trạng Thái");

        btaddnew.setText("Thêm mới");
        btaddnew.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btaddnewActionPerformed(evt);
            }
        });

        btrefresh.setText("Làm mới");
        btrefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btrefreshActionPerformed(evt);
            }
        });

        btdelete.setText("Xóa");
        btdelete.setEnabled(false);
        btdelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btdeleteActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(rbstatus))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btaddnew, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btrefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(btdelete, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(10, 10, 10)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbstatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(rbstatus))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btaddnew)
                            .addComponent(btrefresh)
                            .addComponent(btdelete)))
                    .addComponent(jScrollPane2))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void cbstatusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbstatusActionPerformed
        // TODO add your handling code here:
        clearAll();
        listTypeOfUse.clear();
        boolean status = false;
        if (cbstatus.getSelectedIndex() == 0) {
            status = true;
        }
        listTypeOfUse = hibernateDAOFactory.getTypeOfUseDAO().findAllByStatus(status);
        showList(listTypeOfUse);
    }//GEN-LAST:event_cbstatusActionPerformed

    private void btaddnewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btaddnewActionPerformed
        // TODO add your handling code here:
        try {
            TypeOfUse statusOfUse = new TypeOfUse();
            if (btaddnew.getText().equals("Thêm mới")) {
                statusOfUse.setName(txtname.getText());
                statusOfUse.setDescription(txtdescription.getText());
                statusOfUse.setModifiedDate(new java.sql.Date(Calendar
                    .getInstance().getTimeInMillis()));
            statusOfUse.setStatus(rbstatus.isSelected());
            validInsertTypeOfUse(statusOfUse);
        } else {
            int selectedIndex = tbtypeofuse.getSelectedRow();
            if (selectedIndex != -1) {
                statusOfUse = listTypeOfUse.get(listTypeOfUse
                    .size() - 1 - selectedIndex);
                statusOfUse.setName(txtname.getText());
                statusOfUse.setDescription(txtdescription.getText());
                statusOfUse.setStatus(rbstatus.isSelected());
                statusOfUse.setModifiedDate(new java.sql.Date(Calendar
                    .getInstance().getTimeInMillis()));
            validInsertTypeOfUse(statusOfUse);
            btaddnew.setText("Thêm mới");
            btrefresh.setText("Làm mới");
        }
        }
        this.txtname.requestFocus();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(this,
                "Thêm mới đơn vị sử dụng lỗi!\n Lỗi: " + ex.getMessage(),
                "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
        txtname.selectAll();
        rbstatus.setSelected(true);
    }//GEN-LAST:event_btaddnewActionPerformed

    private void btrefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btrefreshActionPerformed
        // TODO add your handling code here:
        if (btrefresh.getText().equals("Làm mới")) {
            txtname.setText("");
            txtdescription.setText("");
            rbstatus.setSelected(true);
        } else {
            clearAll();
        }
    }//GEN-LAST:event_btrefreshActionPerformed

    private void btdeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btdeleteActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(this, "Bạn có chắc chắn?", "Cảnh báo",
            JOptionPane.WARNING_MESSAGE) == JOptionPane.OK_OPTION) {
        try {
            if (tbtypeofuse.getSelectedRow() != -1) {
                deleteRow(tbtypeofuse.getSelectedRow());
                TypeOfUse statusOfUse = listTypeOfUse.get(listTypeOfUse.size() - 1 - tbtypeofuse.getSelectedRow());
                hibernateDAOFactory.getTypeOfUseDAO().makeTransient(statusOfUse);
                btaddnew.setText("Thêm mới");
                btrefresh.setText("Làm mới");
                btdelete.setEnabled(false);
            }
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Không thể xóa được, "
                + "đơn vị sử dụng này đã được sử dụng!\n");
        }
        }
    }//GEN-LAST:event_btdeleteActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btaddnew;
    private javax.swing.JButton btdelete;
    private javax.swing.JButton btrefresh;
    private javax.swing.JComboBox cbstatus;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JRadioButton rbstatus;
    private javax.swing.JTable tbtypeofuse;
    private javax.swing.JTextArea txtdescription;
    private javax.swing.JTextField txtname;
    // End of variables declaration//GEN-END:variables

   @Override
    public void deleteRow(int index) {
        if (modelTableTypeOfUse.getRowCount() > 0) {
            if (index > 0) {
                tbtypeofuse.setRowSelectionInterval(index - 1, index - 1);
                modelTableTypeOfUse.removeRow(index);
            } else {
                tbtypeofuse.setRowSelectionInterval(index + 1, index + 1);
                modelTableTypeOfUse.removeRow(0);
            }
        } else {
            JOptionPane.showMessageDialog(this, "Không có dòng nào để xóa!",
                    "Cảnh báo!", JOptionPane.WARNING_MESSAGE);
        }
    }

    @Override
    public void updateRow(TypeOfUse row, int index) {
        modelTableTypeOfUse.setValueAt(row.getName(), index, 0);
        if (row.isStatus()) {
            modelTableTypeOfUse.setValueAt("Hiện", index, 1);
        } else {
            modelTableTypeOfUse.setValueAt("Ẩn", index, 1);
        }
    }

    @Override
    public void addRow(TypeOfUse row, boolean posion) {
        String status = "Hiện";
        if (!row.isStatus()) {
            status = "Ẩn";
        }
        if (posion) {
            modelTableTypeOfUse.insertRow(0, new Object[]{row.getName() + "",
                        status});
        } else {
            modelTableTypeOfUse.insertRow(tbtypeofuse.getRowCount(),
                    new Object[]{row.getName() + "", status});
        }
        listTypeOfUse.add(row);
    }

    @Override
    public final void showList(List<TypeOfUse> list) {
        String status;
        int totalrow = tbtypeofuse.getRowCount();
        if (totalrow > 0) {
            for (int i = 0; i < totalrow; i++) {
                modelTableTypeOfUse.removeRow(0);
            }
        }
        if (list != null && list.size() > 0) {
            for (TypeOfUse item : list) {
                if (item.isStatus()) {
                    status = "Hiện";
                } else {
                    status = "Ẩn";
                }
                modelTableTypeOfUse.insertRow(0, new Object[]{item.getName()
                            + "", status});
            }
        }
    }

    @Override
    public void showDetail(TypeOfUse object) {
        txtname.setText(object.getName());
        txtdescription.setText(object.getDescription());
        rbstatus.setSelected(object.isStatus());
    }

    @Override
    public TypeOfUse getObject(int index) {
        TypeOfUse author = new TypeOfUse();
        try {
            if (listTypeOfUse != null && listTypeOfUse.size() > 0 && cbstatus.isFocusOwner() == false) {
                int indexOfList = listTypeOfUse.size() - 1 - index;
                author = listTypeOfUse.get(indexOfList);
            }
        } catch (ArrayIndexOutOfBoundsException ex) {
        }
        return author;
    }

    @Override
    public void setObject(TypeOfUse object) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public boolean validObject(TypeOfUse object) {
        if (object.getName().equals("") || object.getName() == null) {
            JOptionPane.showMessageDialog(this, "Tên đơn vị sử dụng chưa được nhập!");
            return false;
        }
        return true;
    }

    public final void listSelectionListener() {
        tbtypeofuse.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int rowSelected = tbtypeofuse.getSelectedRow();
                showDetail(getObject(rowSelected));
                btaddnew.setText("Sửa");
                btrefresh.setText("Hủy");
                btdelete.setEnabled(true);
            }
        });
    }

    public final void listenerTableModel() {
        modelTableTypeOfUse.addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.DELETE && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Xóa thành công!");
                } else if (e.getType() == TableModelEvent.INSERT && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Thêm đơn vị sử dụng thành công!");
                } else if (e.getType() == TableModelEvent.UPDATE && e.getColumn() == 1 && cbstatus.isFocusOwner() == false) {
                    JOptionPane.showMessageDialog(null, "Sửa đơn vị sử dụng thành công!");
                }
            }
        });
    }

    private void validInsertTypeOfUse(TypeOfUse statusOfUse) {
        if (validObject(statusOfUse)) {
            TypeOfUse statusOfUseResult = hibernateDAOFactory.getTypeOfUseDAO().makePersistent(statusOfUse);
            showDetail(statusOfUseResult);
            if (btaddnew.getText().equals("Thêm mới")) {
                addRow(statusOfUse, true);
            } else {
                updateRow(statusOfUse, tbtypeofuse.getSelectedRow());
            }
        }
    }

    private void clearAll() {
        txtname.setText("");
        txtdescription.setText("");
        rbstatus.setSelected(true);
        btaddnew.setText("Thêm mới");
        btrefresh.setText("Làm mới");
        btdelete.setEnabled(false);
    }
}
